// 获取滚动坐标
export const getScrollPosition = (el = window) => ({
    x: el.pageXOffset !== undefined ? el.pageXOffset :  el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset :  el.scrollTop,
})

// el是否在视口范围内
export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
    const { top, left, bottom, right } = el.getBoundingClientRect()
    const { innerHeight, innerWidth } = window
    return partiallyVisible
        ? ((top > 0 && innerHeight) || (bottom > 0 && bottom < innerHeight) ) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) :
        top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth
}

// 格式化时间戳 以下为示例：
// timestampToDate(时间戳, 'YYYY-MM-DD HH:mm:ss')
export const timestampToDate = (timestamp, format) => {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000); // 转换为毫秒
    const year = date.getFullYear()
    const month = date.getMonth() + 1 // 月份
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    // 格式化字符串
    const formatMap = {
        'YYYY': year,
        'MM': month < 10 ? '0' + month : month,
        'DD': day < 10 ? '0' + day : day,
        'HH': hour < 10 ? '0' + hour : hour,
        'mm': minute < 10 ? '0' + minute : minute,
        'ss': second < 10 ? '0' + second : second
    };
    return format.replace(/YYYY|MM|DD|HH|mm|ss/g, matched => formatMap[matched])
}

// 防抖 以下为示例：
// handleDebounceClick: debounce(function() {
//  console.log('防抖点击')
// }, 1000)
export const debounce = (func, wait) => {
    let timeout
    return function () {
        const context = this
        const args = arguments
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            func.apply(this, args)
        }, wait)
    }
}

// 节流 以下为示例：
// handleThrottleClick: throttle(function() {
//  console.log('节流点击')
// }, 1000)
export const throttle = (func, limit) => {
    let inThrottle
    return function () {
        const args = arguments
        const context = this
        if(!inThrottle) {
            func.apply(context, args)
            inThrottle = true
            setTimeout(() => inThrottle = false, limit)
        }
    }
}
